﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="SetupHandler.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the SetupHandler IHttpHanlder implementation class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Lidocaine
{
    using System;
    using System.Data;
    using System.Data.SqlClient;
    using System.Globalization;
    using System.IO;
    using System.Web;
    using System.Xml;
    
    /// <summary>
    /// Defines the SetupHandler class.
    /// </summary>
    public class SetupHandler : IHttpHandler
    {
        #region Properties
        /// <summary>Gets a value indicating whether this implementation of IHttpHandler is reusable.</summary>
        public bool IsReusable
        {
            get { return false; }
        }
        #endregion

        #region Methods
        /// <summary>
        /// This implementation of IHttpHandler handles one of two asynchronous calls the Lidocaine installation webpage makes.
        /// </summary>
        /// <param name="context">The HttpContext object of the current HTTP request.</param>
        public void ProcessRequest(HttpContext context)
        {
            if (Environmental.AllowSetup)
            {
                using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
                {
                    conn.Open();
                    using (SqlCommand cmd = new SqlCommand("Lidocaine.CreateSite", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ApplicationName", context.Request["siteDomain"]);
                        Profile profile = new Profile(Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture));
                        profile.LogOn(true);
                    }
                }
            
                /*XmlDocument existingConfig = new XmlDocument();
                existingConfig.Load(new StringReader(File.OpenText(HttpContext.Current.Server.MapPath("~/") + "web.config").ReadToEnd()));
            
                // Lidocaine appConfig
                XmlNode appConfig = existingConfig.SelectSingleNode("/configuration/lidocaine/appConfig");
                appConfig.Attributes["allowSetup"].Value = "false";
                appConfig.ParentNode.ReplaceChild(appConfig, existingConfig.SelectSingleNode("/configuration/lidocaine/appConfig"));

                existingConfig.Save(HttpContext.Current.Server.MapPath("~/") + "web.config");
                */
            }
        }
        #endregion
    }
}